﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.SqlClient;

namespace KnowledgeEntity
{
   public class ArticleHistory
   {
      public int ArticleID { get; private set; }

      public Dictionary<int, Article> VersionControlledArticles { get; private set; }

      private ArticleHistory()
      {
         VersionControlledArticles = new Dictionary<int, Article>();
      }

      public static ArticleHistory FetchArticleHistoryById(int articleID)
      {
         ArticleHistory history = new ArticleHistory();

         history.ArticleID = articleID;

         string query = string.Format(@"select ac.ID,ac.Title,ac.Article,ac.VersionID,ac.IsCheckedOut,ac.CheckedOutTime
                           ,lbl.ID,lbl.Code,lbl.Description
                           from VersionControlledArticle ac
                           left join Link_Article_Label lnk on lnk.ArticleID = ac.ID
                           left join CustomizedLabel lbl on lnk.LabelID = lbl.ID
                           where ac.ID = {0}", articleID);

         using (SqlDataReader ArticleHistoryReader = DBHelper.SqlHelper.GetReader(query))
         {
            while (ArticleHistoryReader.Read())
            {
               int versionID = ArticleHistoryReader.GetInt32(3);
               if (!history.VersionControlledArticles.ContainsKey(versionID))
               {
                  history.VersionControlledArticles.Add(versionID,
                                                new Article
                                                {
                                                   ArticleID = ArticleHistoryReader.GetInt32(0),
                                                   Title = ArticleHistoryReader.GetString(1),
                                                   Content = ArticleHistoryReader.GetString(2),
                                                   VersionID = ArticleHistoryReader.GetInt32(3),
                                                   IsCheckedOut = ArticleHistoryReader.GetBoolean(4),
                                                   CheckedOutTime = ArticleHistoryReader.GetDateTime(5)
                                                });

               }
               history.VersionControlledArticles[versionID].AddLabel(new CustomizedLabel
                                                            {
                                                               Code = ArticleHistoryReader.GetString(7),
                                                               Description = ArticleHistoryReader.GetString(8)
                                                            });
            }
            return history;
         }
      }
   }
}
